<template>
  <BasicContainer>
    <ElCard>
      <template #header>
        <div class="clearfix">
          <span>意见</span>
        </div>
      </template>
      <ElForm>
        <ElRow>
          <ElButton v-if="visibleApproveBtn" type="primary" @click="doApprove()">同意</ElButton>
          <ElButton v-if="userTaskConfigObj.disabledBtnJson.turnBtn" type="primary" plain @click="doAssignTask()">
            转办
          </ElButton>
          <ElButton v-if="userTaskConfigObj.disabledBtnJson.delegateBtn" type="primary" plain @click="doDelegateTask()">
            委派
          </ElButton>
          <ElButton v-if="visibleReturnBtn" type="primary" plain @click="doReturnTask()">回退</ElButton>
          <ElButton
            v-if="userTaskConfigObj.disabledBtnJson.beforeSignBtn"
            type="primary"
            plain
            @click="doBeforeAddSignTask()">
            前加签
          </ElButton>
          <ElButton
            v-if="userTaskConfigObj.disabledBtnJson.afterSignBtn"
            type="primary"
            plain
            @click="doAfterAddSignTask()">
            后加签
          </ElButton>
          <ElButton v-if="userTaskConfigObj.disabledBtnJson.reverseSign" type="primary" plain @click="doUnClaimTask()">
            反签收
          </ElButton>
          <ElButton v-if="visibleSendBtn" type="primary" plain @click="handleSendUserTask()">发送</ElButton>
          <ElButton v-if="userTaskConfigObj.disabledBtnJson.stopBtn" type="warning" plain @click="doStopProcess()">
            终止
          </ElButton>
          <ElButton type="warning" plain @click="doBpmnPreview()">查看流程图</ElButton>
        </ElRow>
      </ElForm>
    </ElCard>
    <!-- 用户信息 -->
    <SelectMultipleUser
      :visible.sync="visibleUser"
      :selection="selection"
      :multiple="multiple"
      @getUserList="getUserList" />
    <!-- 回退 -->
    <ReturnTaskUserModel
      ref="returnTaskUserModel"
      :visible.sync="visibleReturn"
      :task-id="taskId"
      :process-instance-id="procInstId"
      @getHandleRecordActivityInfo="getHandleRecordActivityInfo" />
    <!-- 加签 -->
    <AddSignatureModel :visible.sync="visibleSignature" @getAddSignature="getAddSignature" />

    <!-- 自由发送 -->
    <SendUserTaskModel
      ref="sendUserTaskModel"
      :visible.sync="visibleSendUserTask"
      :task-id="taskId"
      @getSendUserTask="getSendUserTask" />
    <!-- 办理意见 -->
    <ApprovalMessageModel ref="approvalMessageModel" :visible.sync="visibleMessageModel" @getMessage="getMessage" />
  </BasicContainer>
</template>

<script>
  import {
    complete,
    stopProcess,
    assignTask,
    delegateTask,
    taskReturn,
    beforeAddSignTask,
    afterAddSignTask,
    sendUserTask,
    nextFlowNodeList,
    taskReject,
    findReturnTaskList,
    unClaimTask
  } from '@/api/admin/workitem'

  import { getUserTaskConfigObj, getObj } from '@/api/admin/actusertaskconfig'
  import ReturnTaskUserModel from '@/module/process/components/ReturnTaskUserModel'
  import AddSignatureModel from '@/module/process/components/AddSignatureModel'
  import SendUserTaskModel from '@/module/process/components/SendUserTaskModel'
  import ApprovalMessageModel from '@/module/process/components/ApprovalMessageModel'

  export default {
    components: {
      ReturnTaskUserModel,
      AddSignatureModel,
      SendUserTaskModel,
      ApprovalMessageModel
    },
    data() {
      return {
        visible: false,
        canSubmit: true,
        dataForm: {
          id: 0,
          processInstanceId: '',
          applyerCode: '',
          title: '',
          type: '1',
          days: '',
          startTime: '',
          endTime: '',
          companyId: '',
          companyName: '',
          deptId: '',
          deptName: '',
          note: '',
          createTime: '',
          creator: '',
          updateTime: '',
          updator: ''
        },
        approveMsg: '',
        procInstId: -1,
        taskId: '',
        visibleUser: false,
        userObj: {},
        userSelectType: -1,
        addSignatureType: -1,
        visibleReturn: false,
        visibleSignature: false,
        selection: true,
        multiple: false,
        visibleSendUserTask: false,
        flowNodeList: [],
        visibleSendBtn: true,
        visibleApproveBtn: true,
        visiblePreview: false,
        routeParams: {
          taskId: '',
          procInstId: '',
          businessKey: '',
          activityId: '',
          activityName: '',
          modelkey: ''
        },
        visibleMessageModel: false,
        visibleReturnBtn: true,
        returnTaskList: [],
        userTaskConfigObj: {
          disabledBtnJson: {
            turnBtn: true,
            afterSignBtn: true,
            beforeSignBtn: true,
            delegateBtn: true,
            reverseSign: true,
            stopBtn: true
          }
        },
        hideFormField: ['days', 'startTime'],
        visibleHideFormField: {
          days: true,
          startTime: true
        }
      }
    },
    created() {
      this.routeParams = this.$route.params
      this.procInstId = this.routeParams.procInstId
      this.taskId = this.routeParams.taskId
      this.init(this.routeParams.businessKey)
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.canSubmit = true
        this.$nextTick(() => {
          this.$refs.dataForm.resetFields()
          if (this.dataForm.id) {
            getObj(this.dataForm.id).then(response => {
              this.dataForm = response.data.data
            })
          }
        })

        // 获取当前任务配置信息。
        getUserTaskConfigObj(this.procInstId, this.taskId, this.routeParams.activityId).then(response => {
          this.userTaskConfigObj = response.data.data
          // console.log(this.userTaskConfigObj)
          this.handleHideFormField()
        })

        // 查询下个环节
        nextFlowNodeList({ taskId: this.taskId }).then(response => {
          this.flowNodeList = response.data.data
          if (!response.data.success) {
            this.visibleSendBtn = false
          } else {
            this.visibleApproveBtn = false
          }
        })

        // 查询回退环节
        const params = { taskId: this.taskId, processInstanceId: this.procInstId }
        findReturnTaskList(params).then(response => {
          this.returnTaskList = response.data.data
          if (!this.returnTaskList.length > 0) {
            this.visibleReturnBtn = false
          }
        })
      },
      handleChange(val) {
        // console.log(val)
      },
      doApprove() {
        if (this.$isBlank(this.approveMsg)) {
          this.$message.warning('请输入审批意见！')
          return
        }
        const taskId = this.routeParams.taskId
        const procInstId = this.routeParams.procInstId
        const params = {
          taskId,
          processInstanceId: procInstId,
          message: this.approveMsg,
          commentTypeEnum: 'SP',
          processStatusEnum: 'SPZ'
        }
        complete(params).then(response => {
          if (response.data.success) {
            this.$message.warning('审批成功。')
            this.closeTag()
          }
        })
      },
      doStopProcess() {
        if (this.$isBlank(this.approveMsg)) {
          this.$message.warning('请输入终止意见！')
          return
        }
        const taskId = this.routeParams.taskId
        const procInstId = this.routeParams.procInstId
        const params = {
          taskId,
          processInstanceId: procInstId,
          message: this.approveMsg,
          commentTypeEnum: 'BH',
          processStatusEnum: 'BH'
        }
        this.$confirm('是否终止该条流程信息？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            stopProcess(params).then(response => {
              if (response.data.success) {
                this.$message.warning('终止成功。')
                this.$closeTab(this.tag)
                this.$router.go(-1)
              }
            })
          })
          .then(() => {})
      },
      getUserList(userList) {
        this.userObj = userList
        const data = {
          taskId: this.routeParams.taskId,
          assignee: this.userObj.username,
          message: this.approveMsg,
          processInstanceId: this.routeParams.procInstId,
          activityId: this.routeParams.activityId,
          activityName: this.routeParams.activityName
        }
        // 转办
        if (this.userSelectType === 0) {
          this.$confirm(`是否将该任务转办至${this.userObj.realName}办理？`, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            data.processStatusEnum = 'ZB'
            assignTask(data).then(response => {
              if (response.data.success) {
                this.$message.success('转办成功。')
                this.$closeTab(this.tag)
                this.$router.go(-1)
              }
            })
          })
        }
        // 委派
        if (this.userSelectType === 1) {
          this.$confirm(`是否将该任务委派至${this.userObj.realName}办理？`, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            data.processStatusEnum = 'WP'
            delegateTask(data).then(response => {
              if (response.data.success) {
                this.$message.success('委派成功。')
                this.$closeTab(this.tag)
                this.$router.go(-1)
              }
            })
          })
        }
      },
      getHandleRecordActivityInfo(obj) {
        const data = {
          message: obj.comment,
          distFlowElementId: obj.activityId,
          activityId: this.routeParams.activityId,
          activityName: this.routeParams.activityName,
          taskId: this.taskId,
          processInstanceId: this.procInstId,
          processStatusEnum: 'TH',
          variables: {
            approval: obj.userCode,
            userList: obj.userCode.split(','),
            days: this.dataForm.days
          }
        }
        this.$confirm('是否退回该任务？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          taskReturn(data).then(response => {
            if (response.data.success) {
              this.$message.success('退回成功！')
              this.$closeTab(this.tag)
              this.$router.go(-1)
            }
          })
        })
      },
      doAssignTask() {
        if (this.$isBlank(this.approveMsg)) {
          this.$message.warning('请输入转办意见！')
          return
        }
        this.userSelectType = 0
        this.visibleUser = true
        this.selection = true
        this.multiple = false
      },
      doDelegateTask() {
        if (this.$isBlank(this.approveMsg)) {
          this.$message.warning('请输入委派意见！')
          return
        }
        this.userSelectType = 1
        this.visibleUser = true
        this.selection = true
        this.multiple = false
      },
      doReturnTask() {
        this.visibleReturn = true
        this.$refs.returnTaskUserModel.setReturnTaskList(this.returnTaskList)
      },
      doBeforeAddSignTask() {
        this.addSignatureType = 0
        this.visibleSignature = true
        this.selection = true
        this.multiple = true
      },
      doAfterAddSignTask() {
        this.addSignatureType = 1
        this.visibleSignature = true
        this.selection = true
        this.multiple = true
      },
      getAddSignature(signature) {
        const data = {
          signPersoneds: signature.signPersoneds,
          message: signature.message,
          activityId: this.routeParams.activityId,
          activityName: this.routeParams.activityName,
          taskId: this.taskId,
          processInstanceId: this.procInstId,
          processStatusEnum: 'SPZ'
        }
        if (this.addSignatureType === 0) {
          // 前加签
          beforeAddSignTask(data).then(response => {
            if (response.data.success) {
              this.$message.success(response.data.msg)
              this.closeTag()
            }
          })
        } else {
          // 后加签
          afterAddSignTask(data).then(response => {
            if (response.data.success) {
              this.$message.success(response.data.msg)
              this.closeTag()
            }
          })
        }
      },
      handleSendUserTask() {
        this.$refs.sendUserTaskModel.setFlowNodeList(this.flowNodeList)
        this.visibleSendUserTask = true
      },
      getSendUserTask(obj) {
        const taskId = this.routeParams.taskId
        const procInstId = this.routeParams.procInstId
        const params = {
          taskId,
          processInstanceId: procInstId,
          message: obj.message,
          commentTypeEnum: 'SP',
          processStatusEnum: 'SPZ',
          activityId: this.routeParams.activityId,
          activityName: this.routeParams.activityName,
          variables: {
            approval: obj.approval.join(','),
            userList: obj.approval,
            days: this.dataForm.days
          }
        }
        if (obj.complete) {
          complete(params).then(response => {
            if (response.data.success) {
              this.$message.warning('审批成功。')
              this.closeTag()
            }
          })
        } else {
          // 自由审批
          params.distFlowElementId = obj.activityId
          sendUserTask(params).then(response => {
            if (response.data.success) {
              this.$message.warning(response.data.msg)
              this.closeTag()
            }
          })
        }
      },
      doUnClaimTask() {
        if (this.$isBlank(this.approveMsg)) {
          this.$message.warning('请输入反签收意见！')
          return
        }
        const taskId = this.routeParams.taskId
        const procInstId = this.routeParams.procInstId
        const params = {
          taskId,
          processInstanceId: procInstId,
          message: this.approveMsg,
          commentTypeEnum: 'FQS',
          processStatusEnum: 'DQS',
          activityId: this.routeParams.activityId,
          activityName: this.routeParams.activityName
        }
        this.$confirm('是否反签收该任务？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          unClaimTask(params).then(response => {
            if (response.data.success) {
              this.$message.warning(response.data.msg)
              this.closeTag()
            }
          })
        })
      },
      doBpmnPreview() {
        this.visiblePreview = true
      },
      getMessage(message) {
        const data = {
          message,
          activityId: this.routeParams.activityId,
          activityName: this.routeParams.activityName,
          taskId: this.taskId,
          processInstanceId: this.procInstId,
          processStatusEnum: 'BH',
          commentTypeEnum: 'BH'
        }
        // 驳回
        taskReject(data).then(response => {
          if (response.data.success) {
            this.$message.success(response.data.msg)
            this.closeTag()
          } else {
            this.$message.error(response.data.msg)
            this.closeTag()
          }
        })
      },
      handleHideFormField() {
        // 处理表单的显示和隐藏。
        const hideFormJson = this.userTaskConfigObj.hideFormJson
        this.hideFormField.forEach(field => {
          if (!this.$isBlank(hideFormJson[field])) {
            this.visibleHideFormField[field] = hideFormJson[field]
          }
        })
      }
    }
  }
</script>
